<?php

namespace Cola;


use Cola\Exception\CanLog;
use Suikachan\ExceptionHandlers\Handle\Handle;

class ExceptionHandle implements Handle
{

    public function report(\Throwable $e)
    {
        $log = [];

        $log['file'] = $e->getFile();
        $log['line'] = $e->getLine();

        $log['msg'] = $e->getMessage();

        $this->simplifyMessage($log);

        $log['basename'] = pathinfo($log['file'], PATHINFO_BASENAME);

        if($e instanceof CanLog)
        {
            $log['extend'] = $e->log();
        }

        logfile('error', $log);
    }
    
    protected function simplifyMessage(&$log)
    {
        if(stripos($log['msg'], 'Stack trace') !== false)
        {
            $log['msg'] = explode('Stack trace', $log['msg'])[0];
        }

        if(stripos($log['msg'], ' in ') !== false)
        {
            $msg = explode(' in ', $log['msg']);

            if( ! empty($msg[1]))
            {
                $file_and_line = preg_split('/:| on line /', $msg[1]);
                if( ! empty($file_and_line[1]))
                {
                    list($log['file'], $log['line']) = $file_and_line;
                    $log['msg'] = $msg[0];
                }
            }
        }

        $log['msg'] = str_replace(['Error:', 'Parse error:'], '', $log['msg']); // 去掉一些多余的字符
    }

    public function dontReport(\Throwable $e)
    {
        return false;
    }
}